﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using eRechnung.Properties;
using eRechnung.ExtensionMethods;


namespace eRechnung
{

    public partial class FrmDetailsBund : Form
    {
#if DEBUG
        private const int MaxRows = 19;
#else
        private const int MaxRows = 999;
#endif

        public FrmDetailsBund()
        {
            Debug.WriteLine("FrmDetails");
            InitializeComponent();
            eRechnung.Globals.ThisDocument.FillDetailsDataGrid(this.dsInvoice);
            if (Settings.Default.SetVStBerechtigt != true)
            {
                dataGridView1.Columns["spMwSt"].Visible = false;
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            Debug.WriteLine("BtnCancel_Click");
            this.Close();
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            Debug.WriteLine("BtnSave_Click");
            int cnt = dsInvoice.TblInvDetails.Rows.Count;
            if (cnt > MaxRows)
            {
                MessageBox.Show("Max. " + MaxRows.ToString() + " Rechnungspositionen zulässig.", 
                                "Eingabefehler",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }
            eRechnung.Globals.ThisDocument.SaveDetails(this.dsInvoice);
            this.Close();
        }


        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            Debug.WriteLine("dataGridView1_CellValidating");

            if (BtnCancel.Focused == true)
            {
                return;
            }
            DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
            string errorTxt = string.Empty;
            DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
            cell.ErrorText = "";
            string ColName = dataGridView1.Columns[e.ColumnIndex].Name;
            decimal colValue = 0;

            switch (ColName)
            {
                case "spEinzelpreis": // lt. E-Mail von Hr. Helger darf der Einzelpreis jeden Wert annehmen.
                case "spMenge":
                        if (!decimal.TryParse(e.FormattedValue.ToString(), out colValue))
                        {
                            errorTxt = dataGridView1.Columns[e.ColumnIndex].HeaderText + " ist nicht numerisch.";
                            e.Cancel = true;                            
                        } 

                    break;
                case "spRabattProz":
                    try
                    {
                        colValue = decimal.Parse(e.FormattedValue.ToString());
                        if (colValue < 0)
                        {
                            errorTxt = dataGridView1.Columns[e.ColumnIndex].HeaderText + " darf nicht kleiner Null sein.";
                            e.Cancel = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        errorTxt = dataGridView1.Columns[e.ColumnIndex].HeaderText + " ist nicht numerisch.";
                        e.Cancel = true;
                    }

                    break;
                default:
                    break;
            }

            if (e.Cancel == false)
            {
                switch (ColName)
                {
                    case "spRabattProz":
                        if ((e.FormattedValue != null) && (e.Cancel == false))
                        {
                            if (decimal.Parse(e.FormattedValue.ToString()) >= 100)
                            {
                                errorTxt = "Rabatt % muss kleiner 100 sein.";
                                e.Cancel = true;
                            }
                            if (decimal.Parse(e.FormattedValue.ToString()) < 0)
                            {
                                errorTxt = "Rabatt % muss größer/gleich 0 sein.";
                                e.Cancel = true;
                            }
                        }
                        break;
                    case "SpBestellBezug":
                        e.Cancel = !Globals.ThisDocument.IsBestellBezugValid(e.FormattedValue as string, out errorTxt);
                        break;
                    default:
                        break;

                }
            }


            if (e.Cancel == true)
            {
                MessageBox.Show(errorTxt, "Eingabefehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // cell.ErrorText = errorTxt;
            }

        }


        private void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            Debug.WriteLine("dataGridView1_DefaultValuesNeeded");

            e.Row.Cells["spRabattProz"].Value = 0;
            e.Row.Cells["spMwSt"].Value = Settings.Default.setMwStDefault;

        }
        private bool SetCancel(bool current, bool OkValue)
        {
            Debug.WriteLine("SetCancel");

            if (current == true)
            {
                return true;
            }
            return OkValue;
        }
        private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (BtnCancel.Focused == true)
            {
                return;
            }
            Debug.WriteLine("dataGridView1_RowValidating");
            DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
            dataGridView1.Rows[e.RowIndex].ErrorText = "";

            // Zeilenvalidierung ausgeschaltet, da eher nicht gut
            foreach (DataGridViewCell cell in row.Cells)
            {
                cell.ErrorText = "";
            }
            int anz = (dataGridView1.Rows.Count) - 1;
            if (anz == e.RowIndex)
            {
                e.Cancel = false;
                return;
            }
            DataGridViewCell trackCell = row.Cells[dataGridView1.Columns["spBezeichnung"].Index];
            e.Cancel = SetCancel(e.Cancel, IsStringOK(trackCell, "Artikelbeschreibung feht", "Bitte Artikelbeschreibung eingeben"));

            trackCell = row.Cells[dataGridView1.Columns["spEinheit"].Index];
            e.Cancel = SetCancel(e.Cancel, IsStringOK(trackCell, "Einheit feht", "Bitte Einheit eingeben"));

            decimal menge = 0;
            decimal ePreis = 0;
            trackCell = row.Cells[dataGridView1.Columns["spMenge"].Index];
            e.Cancel = SetCancel(e.Cancel, IsDecimalOK(trackCell, "Menge ist 0", "Bitte Menge eingeben", true, menge));

            trackCell = row.Cells[dataGridView1.Columns["spEinzelpreis"].Index];
            e.Cancel = SetCancel(e.Cancel, IsDecimalOK(trackCell, "Einzelpreis ist 0", "Bitte Einzelpreis eingeben", true, ePreis));

            decimal rabatt = 0;
            trackCell = row.Cells[dataGridView1.Columns["spRabattProz"].Index];
            e.Cancel = SetCancel(e.Cancel, IsDecimalOK(trackCell, "Rabatt % ist nicht numerisch", "Bitte Rabatt % eingeben", true, rabatt));
            trackCell = row.Cells[dataGridView1.Columns["SpBestellBezug"].Index];
            string errtxt;
            if (!Globals.ThisDocument.IsBestellBezugValid(trackCell.FormattedValue as string, out errtxt))
            {
                trackCell.ErrorText = errtxt;
                e.Cancel = true;
            }
            if (e.Cancel == true)
            {
                MessageBox.Show("Fehler in der Zeile. Sie können entweder die Fehler korrigieren oder Zeile löschen.", "Details bearbeiten", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool IsDecimalOK(DataGridViewCell cell, string errTxtCell, string errTxtRow, bool AllowZero, decimal value)
        {
            Debug.WriteLine("IsDecimalOK");
            cell.ErrorText = "";
            if (cell.Value == null)
            {
                return false;
            }
            string editValue = cell.EditedFormattedValue.ToString();
            if (editValue.Length == 0)
            {
                cell.ErrorText = errTxtCell;
                dataGridView1.Rows[cell.RowIndex].ErrorText = errTxtRow;
                return true;
            }

            try
            {
                value = decimal.Parse(editValue);
                if ((value == 0) && (AllowZero != true))
                {
                    cell.ErrorText = errTxtCell;
                    dataGridView1.Rows[cell.RowIndex].ErrorText = errTxtRow;
                    return true;
                }
            }
            catch (Exception ex)
            {
                cell.ErrorText = errTxtCell;
                dataGridView1.Rows[cell.RowIndex].ErrorText = errTxtRow;
                return true;
            }

            return false;
        }

        private Boolean IsStringOK(DataGridViewCell cell, string errTxtCell, string errTxtRow)
        {
            Debug.WriteLine("IsStringOK");
            cell.ErrorText = "";
            if (cell.Value == null)
            {
                return false;
            }
            if (cell.Value.ToString().Length == 0)
            {
                cell.ErrorText = errTxtCell;
                dataGridView1.Rows[cell.RowIndex].ErrorText = errTxtRow;
                return true;
            }
            return false;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            Debug.WriteLine("dataGridView1_CellContentClick");
            int iRowCount = this.dsInvoice.TblInvDetails.Rows.Count;
            if (iRowCount > 0)
            {
                if (this.dataGridView1.Columns[e.ColumnIndex].Name == "BtnDel")
                {
                    this.dataGridView1.Rows.RemoveAt(e.RowIndex);
                }

            }
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            int n = dataGridView1.CurrentCell.ColumnIndex;
            if (this.dataGridView1.Columns[n].Name == "BtnDel")
            {
                dataGridView1.CurrentCell.Selected = false;
            }

        }

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            string feld = this.dataGridView1.Columns[e.ColumnIndex].Name;
            MessageBox.Show("Eingabefehler in " + feld + ".", "Details bearbeiten", MessageBoxButtons.OK, MessageBoxIcon.Error);
            e.Cancel = true;
        }

        private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (BtnCancel.Focused == true)
            {
                return;
            }
            int iRow = e.RowIndex;
            DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
            DataGridViewCell trackCell = row.Cells[dataGridView1.Columns["spRabattProz"].Index];
            DataTable tab = this.dsInvoice.TblInvDetails;
            if (tab.Rows.Count <= iRow)
            {
                return;
            }
            DataRow myRow = tab.Rows[iRow];

            switch (myRow.RowState)
            {
                case DataRowState.Detached:
                    return;
                    break;
                case DataRowState.Unchanged:
                    break;
                case DataRowState.Added:
                    break;
                case DataRowState.Deleted:
                    return;
                    break;
                case DataRowState.Modified:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            if (myRow["spRabattProz"] == DBNull.Value)
            {
                myRow["spRabattProz"] = 0.00;
            }

        }

        private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.RowCount > MaxRows)
            {
                MessageBox.Show("Max. " + MaxRows.ToString() + " Rechnungspositionen zulässig.", "Eingabefehler", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                dataGridView1.AllowUserToAddRows = false;
            }

        }

        private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            if (dataGridView1.RowCount < MaxRows)
            {
                dataGridView1.AllowUserToAddRows = true;
            }

        }


    }
}
